package angry.courses.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewStudentsServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws  ServletException, IOException {
    	
		res.setContentType("text/html");
    	PrintWriter out = res.getWriter();
    	out.println(new HtmlFormatter() {
    	    public String title() {
    		return "View Students";
    	    }

       	    public void body(StringBuffer buf) {
       	    buf.append(heading(4, "Please choose the student you want to view (leave blank for all students)"));
       	    buf.append("<form method=\"post\" action=\"ViewStudents\">");
       	    buf.append("<table>");
       	    
    		buf.append(tr("Student name:", textbox("name"), button("Submit")));
    		buf.append("</table>");
    		buf.append("<br>Go " + link("back", "index.html") + " to main page.");
    	    }
    	}.htmlTag());
    	out.close();
    }
    
    public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
    	res.setContentType("text/html");
    	final String name = req.getParameter("name");
	    	
    	PrintWriter out = res.getWriter();
    	out.println(new HtmlFormatter() {
    	    public String title() {
    		return "View Students";
    	    }

       	    public void body(StringBuffer buf) {
       	    	StudentDelegate studentDelegate = new StudentDelegate();
       	    	ViewDelegate viewDelegate = new ViewDelegate();
	       	    if (!name.equals("")) {
	       	    	if (!viewDelegate.addStudentToView(buf, this, name)) {
	       	    		buf.append(heading(4, "Student not found<br>"));
	       	    	}
	        	} else {
       	    		List<String> students = studentDelegate.getStudentNames();
       	    		if (students != null && students.size() > 0) {
	       	    		for (String studentName : students) {
	       	    			viewDelegate.addStudentToView(buf, this, studentName);
	       	    		}
       	    		} else {
       	    			buf.append(heading(4, "No student found<br>"));
       	    		}
	        	}
	       	    buf.append("Go " + link("back", "index.html") + " to main page.");
	       	    buf.append("<br>" + link("View", "ViewStudents") + " other students.");
       	    }   	    	
    	}.htmlTag());
    	out.close();
    }
}